package com.xkdx.guangguang.sql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CityDatahelper {
	public static String TAG = "CityDatahelper";
	private SQLiteDatabase db;
	public static String CITYTABNAME = "city";
	public static String CITYNAME = "cityName";
	public static String CITYCODE = "cityID";

	public CityDatahelper(Context context) {
		ReleaseDataBase releaseDataBase = new ReleaseDataBase(context);
//		db = releaseDataBase.OpenCityDataBase();
	}

	public void Close() {
		if (db != null) {
			db.close();
		}
		// dbHelper.close();
	}

	public void insertCity(List<Map<String, String>> list) {
		// db = dbHelper.getWritableDatabase();
		try {

			for (int i = 0; i < list.size(); i++) {
				ContentValues values = new ContentValues();
				values.put(CITYNAME, list.get(i).get("CityName"));
				values.put(CITYCODE, list.get(i).get("CityID"));
				db.insert(CITYTABNAME, null, values);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		// db.close();
	}

	public List<Map<String, String>> getCity() {
		// db = dbHelper.getReadableDatabase();
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		try {
			Cursor cursor = db.query(CITYTABNAME, null, null, null, null, null, null);

			while (cursor.moveToNext()) {
				Map<String, String> map = new HashMap<String, String>();
				map.put(CITYNAME, cursor.getString(cursor.getColumnIndex(CITYNAME)));
				map.put(CITYCODE, cursor.getString(cursor.getColumnIndex(CITYCODE)));
				// Log.i(TAG,
				// cursor.getString(cursor.getColumnIndex(CITYNAME)));
				// Log.i(TAG,
				// cursor.getString(cursor.getColumnIndex(CITYCODE)));
				list.add(map);
			}
			// Close();
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}

	public String getFirstCity() {
		// db = dbHelper.getReadableDatabase();
		String cityID = null;
		try {
			Cursor cursor = db.query(CITYTABNAME, null, null, null, null, null, null);

			while (cursor.moveToFirst()) {
				cityID = cursor.getString(cursor.getColumnIndex(CITYCODE));
			}
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return cityID;
	}

	public void clear() {
		try {
			db.execSQL("DROP TABLE IF EXISTS " + CITYTABNAME);
			db.execSQL("CREATE TABLE IF NOT EXISTS " + CITYTABNAME + "(" + CITYNAME + " varchar primary key,"
					+ CITYCODE + " varchar)");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
